package cn.hwua.web;

import cn.hwua.dao.ShopDao;
import cn.hwua.dao.impl.ShopDaoImpl;
import cn.hwua.entity.News;
import cn.hwua.entity.Shop;
import cn.hwua.util.StringUtil;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/shop/*")
public class ShopServlet extends HttpServlet {
    ShopDao dao = new ShopDaoImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String baseURL = req.getContextPath();//获取项目的基本路径
        String path = BaseServlet.getPath(req, resp);
        System.out.println("path = " + path);
        if ("find.do".equals(path)) {
            find(req, resp);
            return;
        }else if ("show.do".equals(path)){
            List<String> addressList = dao.findAddress();
            req.setAttribute("addressList",addressList);
            req.getRequestDispatcher(baseURL+"/pc/shop.jsp").forward(req,resp);
        }else if ("shop-con.do".equals(path)){
            String shopId = req.getParameter("shopId");
            Shop shop = dao.findById(shopId);
            req.setAttribute("shop",shop);
            req.getRequestDispatcher(baseURL+"/pc/shop-con.jsp").forward(req,resp);
        } else {
            throw new RuntimeException("请求错误");
        }
    }

    private void find(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String shop_name = req.getParameter("shop_name");
        String shop_address = req.getParameter("shop_address");
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtil.isNotEmpty(shop_name)){
            map.put("shop_name",shop_name);
        }
        if (StringUtil.isNotEmpty(shop_address)){
            map.put("shop_address",shop_address);
        }
        List<Shop> shopList = dao.find(map);
        resp.setContentType("application/json;charset=utf-8");
        String json=JSON.toJSONString(shopList);
        PrintWriter out=resp.getWriter();
        out.write(json);
        out.close();
        return;
    }
}
